package operateBusiness;

import com.alibaba.fastjson.JSONArray;
import models.MyConfig;
import models.MyFile;
import models.ReturnJson;
import models.TestServerBusinessImpl;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * Created by yangxianming on 2023/12/4.
 */
public class ReadCSV implements TestServerBusinessImpl {
    // http://localhost:1988/operateExcel/readExcel?excelPath=D:\javaWorkSpace\laboratory\人员信息.xlsx&excelSheetIndex=0
    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig) {
        String csvPath = request.getParameter("csvPath");
        String rowIndex = request.getParameter("rowIndex");


        System.out.println("excelPath:" + csvPath);


        //判断excelPath是目录还是文件
        File file = new File(csvPath);
        if (file.isDirectory()){
            File[] listFiles = file.listFiles();
            long fileCreateTime = 0l;
            String lastTimeFileName = "";
            for (int i = 0; i < listFiles.length; i++) {
                File onefile = listFiles[i];
                if (onefile.isDirectory()){
                    continue;
                }
                if (fileCreateTime < onefile.lastModified()){
                    fileCreateTime = onefile.lastModified();
                    lastTimeFileName = onefile.getPath();
                }
            }
            System.out.println("最近的文件是:" + lastTimeFileName);

            return getFile_info(lastTimeFileName, rowIndex).toString();
        }

        if (file.isFile()){
            return getFile_info(csvPath, rowIndex).toString();
        }

        ReturnJson returnJson = new ReturnJson();
        returnJson.setApiStatus(0);
        returnJson.setResult("can not found excelPath:" + csvPath);
        return returnJson.toString();
    }

    private ReturnJson getFile_info(String csvPath, String rowIndex){
        ReturnJson returnJson = new ReturnJson();
        try {
            int sheetIndex = Integer.valueOf(rowIndex);
            MyFile myFile = new MyFile();
            JSONArray excelMatrix = myFile.readLog(csvPath);
            returnJson.setApiStatus(1);
            returnJson.setResult(excelMatrix);
        }catch (Exception e){
//            e.printStackTrace();
            returnJson.setApiStatus(0);
            returnJson.setResult(e.getMessage());
        }
        return returnJson;
    }
}
